package at.ac.univie.bi.transformation.service.output;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.ZoneId;

import at.ac.univie.bi.transformation.model.output.AbstractOutputEntity;
import at.ac.univie.bi.transformation.model.output.PCP;
import at.ac.univie.bi.transformation.model.output.ProcessCaseActivity;
import at.ac.univie.bi.transformation.persistence.DBHandler;

public class PCAService extends AbstractOutputEntityService {

	@Override
	public int save(AbstractOutputEntity element) {
		int newid = 0;
		if(element instanceof ProcessCaseActivity)
		{
			ProcessCaseActivity pca = (ProcessCaseActivity)element;
			String sqlstatement = "INSERT INTO ProcessCaseActivity (processcaseId, activityId, starttime, stoptime, timeprecision) VALUES ("+ pca.getProcesscaseId() + "," + pca.getActivityId() + ",'" + pca.getStarttime() + "','" + pca.getStoptime() + "'," + pca.getTimeprecision() +")";
			newid = executeInsertStatement(sqlstatement);
		}
		
		return newid;
	}
	
	public void listActivities(){
		  String sqlstatement = "SELECT * FROM ProcesscaseActivity";
		  try
	      {
			  Statement stmt = DBHandler.getIntegrationDB().createStatement();
	          ResultSet results = stmt.executeQuery(sqlstatement);
	          ResultSetMetaData rsmd = results.getMetaData();
	          int numberCols = rsmd.getColumnCount();
	          for (int i=1; i<=numberCols; i++)
	          {
	              //print Column Names
	              System.out.print(rsmd.getColumnLabel(i)+"\t\t");  
	          }

	          System.out.println("\n-------------------------------------------------");

	          while(results.next())
	          {
	        	  
	        	  int id = results.getInt(1);
	              int processcaseId = results.getInt(2);;
	              int activityId = results.getInt(3);
	              System.out.println(id + "\t\t" + processcaseId + "\t\t" + activityId );
	              
	          }
	          results.close();
	          stmt.close();
	      }
	      catch (SQLException sqlExcept)
	      {
	          sqlExcept.printStackTrace();
	      }
	}
	
	public int executeInsertStatement(String sqlstatement){
	  int newid = 0;
	  
	  try
      {
		  String generatedColumns[] = {"ID"};
          PreparedStatement pstmt =  DBHandler.getIntegrationDB().prepareStatement(sqlstatement, generatedColumns);
          pstmt.executeUpdate();
          
          ResultSet rs = pstmt.getGeneratedKeys();
          while (rs.next()){
        	    newid = rs.getInt(1);
          }	
      } 
	  catch (Exception e) {	
			System.err.println("Error: " + e.getMessage());
	  } 
	  
	  return newid;
  	}

}
